package rmhc.gui
{
	import com.adobe.images.PNGEncoder;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.MovieClip;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;
	import flash.utils.Dictionary;
	
	import rmhc.RMHCApp;
	import rmhc.api.ApiWrapper;
	import rmhc.api.dataflow.UserInfo;
	import rmhc.api.dataflow.WallPostInfo;
	import rmhc.api.tasks.IGetFriends;
	import rmhc.api.tasks.IWallPost;
	import rmhc.design.FriendSelectDesign;
	
	public class FriendGrid extends FriendSelectDesign
	{
		protected var grid:ScrollableGrid;
		protected var cells:Vector.<FriendCell>;
		protected var cellCount:int;
		
		protected var postId:String;
		protected var thumbPng:ByteArray;
		protected var thumbSrc:String;
		protected var ap:ApiWrapper;
		protected var gf:IGetFriends;
		protected var list:Vector.<UserInfo>;
		protected var posting:Dictionary = new Dictionary();;
		
		protected var active:FriendCell;
		protected var dragging:Boolean;
		
		public function FriendGrid( postId:String , thumb:BitmapData , thumbSrc:String )
		{
			super();
			this.postId = postId;
			this.thumbSrc = thumbSrc;
			var tm:BitmapData = new BitmapData( thumb.width , thumb.height , false , 0xBD1A1D );
			tm.draw( thumb );
			thumbPng = PNGEncoder.encode( tm );
			
			//grid = new ScrollableGrid(2, 100 , 132 , 20 , 60 );
			grid = new ScrollableGrid(3, 100 , 100 , 20 , 22 );
			//grid.y = 13;
			addChildAt( grid , getChildIndex( btnNext ) );
		}
		
		public function init():void
		{
			//грузим друзей
			ap = RMHCApp.getApi();
			gf = ap.getFriends();
			gf.addEventListener(Event.COMPLETE , onGetFriends );
			gf.run();
		}
		protected function onGetFriends( e:Event ):void
		{
			list = gf.getFriends();
			cells = new Vector.<FriendCell>();
			cellCount = list.length;
			
			var cell:FriendCell;
			for each ( var i:UserInfo in list )
			{
				/*if ( i.thumbSrc == null )
				{
					continue;
				}*/
				cell = new FriendCell( i );
				cells.push( cell );
				cell.addEventListener( Event.COMPLETE , initNextCell );
				cell.addEventListener( MouseEvent.CLICK , onCellClick );
				//добавляем в сетку
				grid.addCell( cell );
			}
			if ( cells.length == 0 )
			{
				return;
			}
			
			//загружаем
			cells[0].init();
			//создаём скролл
			grid.setMaskArea( area );
			grid.setScrollSlider( barSlider );
			grid.initScroll();
			
			initUi();
			dispatchEvent( new Event( Event.CONNECT ) );
		}
		
		protected function initNextCell( e:Event = null ):void
		{
			var i:int = 0;
			if ( e != null )
			{
				var cell:FriendCell = e.target as FriendCell;
				i = cells.indexOf( cell );
				//trace( "cell" , i , "inited, id:" , cell.getInfo().id );
			}
			if ( i + 1 >= cells.length )
			{
				//done
			}
			else
			{
				var next:FriendCell = cells[i + 1];
				next.init();
			}
		}
		
		protected function initUi():void
		{
			if ( grid.isEnabled() )
			{
				//ставим листенеры
				barSlider.addEventListener(MouseEvent.MOUSE_DOWN , onScrollDrag );
				stage.addEventListener(MouseEvent.MOUSE_UP , onScrollDrop );
				stage.addEventListener(MouseEvent.MOUSE_MOVE , onScrollMove );
				btnNext.addEventListener( MouseEvent.CLICK , onBtnNext );
				btnPrev.addEventListener( MouseEvent.CLICK , onBtnPrev );
				addEventListener( MouseEvent.MOUSE_WHEEL , onScrollWheel );
				
				//рисуем подложку для скролла
				var bx:MovieClip = new MovieClip();
				bx.graphics.beginFill( 0 , 0 );
				var r:Rectangle = grid.getBounds( this );
				bx.graphics.drawRect( r.x , r.y , r.width , r.height );
				bx.graphics.endFill();
				grid.addChildAt( bx , 0 );
			}
			else
			{
				barSlider.visible = btnNext.visible = btnPrev.visible = false;
			}
		}
		protected function onBtnNext( e:MouseEvent ):void
		{
			//grid.scrollRight();
			grid.scrollOnce( 1 );
		}
		protected function onBtnPrev( e:MouseEvent ):void
		{
			//grid.scrollLeft();
			grid.scrollOnce( -1 );
		}
		protected function onScrollDrag( e:MouseEvent ):void
		{
			dragging = true;
			grid.dragSlider( true );
		}
		protected function onScrollDrop( e:MouseEvent ):void
		{
			grid.dragSlider( false );
			dragging = false;
		}
		protected function onScrollMove( e:MouseEvent ):void
		{
			if ( dragging )
			{
				grid.updateSliderPos( e );
			}
		}
		protected function onScrollWheel( e:MouseEvent ):void
		{
			//trace( "onScrollWheel" , e.delta );
			var d:Number = e.delta < 0 ? 1 : -1;
			grid.scrollOnce( d );
		}
		
		
		protected function onCellClick( e:MouseEvent ):void
		{
			var cell:FriendCell = e.currentTarget as FriendCell;
			if ( active == cell )
			{
				return;
			}
			
			/*if ( active != null )
			{
				active.setActive( false );
			}*/
			active = cell;
			
			//TODO: постим на стену другу
			var p:WallPostInfo = createPostInfo( cell.getInfo().uid );
			cell.setUsed( true );
			trace( "try post" , p );
			var pw:IWallPost = ap.postToWall( p );
			posting[pw] = cell;
			pw.addEventListener(Event.COMPLETE , onPostDone );
			pw.addEventListener(IOErrorEvent.NETWORK_ERROR , onPostCancel );
			pw.run();
			//active.setActive( true );
			//dispatchEvent( new Event( Event.CHANGE ) );
		}
		protected function onPostDone( e:Event ):void
		{
			var pw:IWallPost = e.target as IWallPost;
			var cell:FriendCell = posting[pw] as FriendCell;
			
			cell.setUsed( true );
		}
		protected function onPostCancel( e:IOErrorEvent ):void
		{
			var pw:IWallPost = e.target as IWallPost;
			var cell:FriendCell = posting[pw] as FriendCell;
			cell.setUsed( false );
			delete posting[pw];
		}
		
		protected function createPostInfo( friendId:String ):WallPostInfo
		{
			var p:WallPostInfo = new WallPostInfo( friendId , "Сообщение из картошки" , "Сообщение из картошки" , WallPostInfo.APP );
			p.postId = postId;
			p.thumbPng = thumbPng;
			p.thumbUrl = thumbSrc;
			return p;
		}
		
		
		/*public function getActive():FriendCell
		{
			if ( active != null )
			{
				return active.getInfo();
			}
			return null;
		}*/
	}
}